﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DriveBeamEditor.Controls.BeamNG;
using WeifenLuo.WinFormsUI.Docking;

namespace DriveBeamEditor.Forms.Docking
{
    public partial class WebBrowserContentForm : DockContent
    {
        #region Fields

        private BeamNGMainForm _beamNgForm;

        #endregion

        #region Properties

        public WebBrowser Control
        {
            get { return Controls.OfType<WebBrowser>().FirstOrDefault(); }
        }

        public BeamNGMainForm BeamNGForm
        {
            get { return _beamNgForm; }
            private set
            {
                if (_beamNgForm != null)
                    UnregisterParentForm();

                _beamNgForm = value;

                if (value != null)
                    RegisterParentForm();
            }
        }

        #endregion

        #region CTORs

        public WebBrowserContentForm()
        {
            InitializeComponent();
        }

        public WebBrowserContentForm(string initialUrl, BeamNGMainForm beamNgForm)
            : this()
        {
            BeamNGForm = beamNgForm;
            webBrowser.Navigate(initialUrl);
        }

        #endregion

        #region Events

        private void OnBrowserUrlChaned(object sender, string url)
        {
            if (Control != null)
                Control.Navigate(url);
        }

        #endregion

        #region Methods

        private void RegisterParentForm()
        {
            BeamNGForm.BrowserUrlChanged += OnBrowserUrlChaned;
        }

        private void UnregisterParentForm()
        {
            BeamNGForm.BrowserUrlChanged -= OnBrowserUrlChaned;
        }

        #endregion
    }
}
